<!--
 * @Autor: 黄旗
 * @Date: 2020-06-03 16:04:09
-->
<template>
    <div>
        <div class="wrapper">
            <template v-if="chatrecordlist && chatrecordlist.length && !spinShow">
                <div v-for="(item, index) in chatrecordlist" :key="item.index" :class="item.isSend ? 'right times' : 'left times'">
                    <div class="name">
                        <div>
                            <img :src="item.avatar" style="margin-right: 15px;"/>
                        </div>
                        <div class="names">
                            <p style="margin-right: 15px;">{{ item.name }}</p>
                            <p style="margin-right: 15px;">
                                {{ changetime(item.create_time) }}
                            </p>
                        </div>
                    </div>
                    <div class="content">
                        <!-- 1：文字  2：图片 3：语音   4:视频消息  5：系统提示  8 : 文件 11:红包 12:转账 14 : 表情  20: 语音通话/视频通话 -->
<!--                        <template v-if="parseInt(item.deleted) === 1">
                            <span style="color:darkgray">消息已撤回</span>
                        </template>-->
                        <!-- 图片 -->
                        <template v-if="parseInt(item.contentType) === 2">
                            <img class="image large-img" :src="decode(item)" @click="leftimgClick(item)">
                        </template>
                        <!-- 语音 -->
                        <template v-else-if="parseInt(item.contentType) === 3">
                            <Button v-if="item.show" type="primary" :disabled="item.loading && item.show" :loading="item.loading" @click="toLoading(index)">
                                <span v-if="!item.loading">加载音频</span>
                                <span v-else>加载中...</span>
                            </Button>
                            <audio :src="decode(item)" controls v-else></audio>
                        </template>
                        <!-- 视频 -->
                        <template v-else-if="parseInt(item.contentType) === 4">
                            <div class="video-box">
                                <img :src="decode(item)" alt="视频" />
                                <div class="video-boxs" @click="leftvideoClick(item)">
                                    <i class="ivu-icon ivu-icon-md-arrow-dropright-circle"></i>
                                </div>
                            </div>
                        </template>
                        <!-- 其他消息 -->
                        <div class="wechatchat" v-else v-html="decode(item)"></div>
                    </div>
                </div>
            </template>
            <div v-else class="norecord">暂无聊天信息</div>

            <Spin size="large" fix v-if="spinShow"></Spin>
        </div>

        <div v-if="chatrecordlist && chatrecordlist.length && !spinShow" class="ivu-mt-8">
            <Row type="flex" justify="space-between" class="code-row-bg">
                <Col span="12">
                    <Button class="ivu-mr-8" type="info" @click="askDatas('all')" :disabled="disabled">加载全部</Button>
                    <Button type="info" @click="exportchat" :disabled="chatrecordlist.length<1">导出图片</Button>
                </Col>
                <Col span="12">
                    <Row type="flex" justify="space-around" class="code-row-bg">
                        <Col span="4">
                            <Button class="ivu-mr-8" type="info" :disabled="+disables.is_show_first === 0 || disabled" @click="askDatas('first')">首次</Button>
                        </Col>
                        <Col span="4">
                            <Button class="ivu-mr-8" type="info" :disabled="+disables.is_show_prev === 0 || disabled" @click="askDatas('prev')">上次</Button>
                        </Col>
                        <Col span="4">
                            <Button class="ivu-mr-8" type="info" :disabled="+disables.is_show_next === 0 || disabled" @click="askDatas('next')">下次</Button>
                        </Col>
                        <Col span="4">
                            <Button class="ivu-mr-8" type="info" :disabled="+disables.is_show_end === 0 || disabled" @click="askDatas('end')">尾次</Button>
                        </Col>
                    </Row>
                </Col>
            </Row>
            <!-- <Button class="ivu-mr-8" type="info" :disabled="+disables.is_show_first===0" @click="askDatas('first')">首次</Button>
            <Button class="ivu-mr-8" type="info" :disabled="+disables.is_show_prev===0" @click="askDatas('prev')">上次</Button>
            <Button class="ivu-mr-8" type="info" :disabled="+disables.is_show_next===0" @click="askDatas('next')">下次</Button>
            <Button class="ivu-mr-8" type="info" :disabled="+disables.is_show_end===0" @click="askDatas('end')">尾次</Button> -->
        </div>

        <!--大图or视频-->
        <Modal v-model="content" :width="80" footer-hide>
            <img v-if="is_img" style="width:100%;height: 80vh;:80%;object-fit: contain;" :src="bigImgUrl" />
            <video v-if="!is_img" style="width:100%;height: 80vh;:80vh;object-fit: contain;" :src="bigImgUrl" controls type="video/mp4" alt="视频"></video>
        </Modal>
    </div>
</template>

<script>
    import { wechatmessagelist } from '@api/hqapi';
    import { customerwechatconverfile, wechatMessageInfo } from '@api/hqapi/indexone.js';
    import dayjs from 'dayjs';
    import phiz from '@/libs/phiz.js';
    export default {
        props: ['paramsrecord'],
        data () {
            return {
                disabled: false,
                spinShow: false,
                total: 0,
                now_date: '',
                type: '',
                disables: '',
                // params: { page: 1, pageSize: 10 },
                chatrecordlist: [],
                // 大图弹框
                content: false,
                is_img: false,
                bigImgUrl: '',
            };
        },
        watch: {
            footData () {
                this.scrollTop();
            }
        },
        methods: {
            // askData () {
            //     this.params.page++
            //     let config = {
            //         wechat_id: this.paramsrecord.wechat_id,
            //         friend_id: this.paramsrecord.friend_id,
            //         page: this.params.page,
            //         pageSize: this.params.pageSize
            //     }
            //     this.spinShow = true
            //     wechatmessagelist(config).then((res) => {
            //         this.total = res.total
            //         this.params.page = res.page
            //         this.params.pageSize = res.pageSize
            //         this.chatrecordlist.unshift(...res.list.reverse())
            //         for (let item of this.chatrecordlist) {
            //             if (item.contentType === '3') {
            //                 if (item.content.indexOf('.amr') !== -1 || item.content.indexOf('.AMR') !== -1) {
            //                     item.show = true
            //                     item.loading = false
            //                 } else {
            //                     item.show = false
            //                 }
            //             }
            //         }
            //         let that = this
            //         setTimeout(()=>{
            //             that.spinShow = false
            //             this.$nextTick(() => {
            //                 let num = this.params.pageSize - 1
            //                 let scrollHeight = document.querySelectorAll('.times')[num].offsetTop
            //                 document.querySelector('.wrapper').scrollTop = scrollHeight + 60
            //             })
            //         },500)
            //     })
            // },
            askDatas (type) {
                this.chatrecordlist = [];
                this.spinShow = true;
                this.params = { page: 1, pageSize: 10 };
                let config = {
                    wechat_id: this.paramsrecord.wechat_id,
                    friend_id: this.paramsrecord.friend_id,
                    type: type || '',
                    now_date: this.now_date
                // pageSize: this.params.pageSize
                };
                this.disabled = type === 'all';
                wechatmessagelist(config).then((res) => {
                    this.total = res.total;
                    this.disables = res.op;
                    this.chatrecordlist.unshift(...res.list.reverse());
                    if (res.list.length > 0) {
                        this.now_date = dayjs(res.list[0].create_time).format(
                            'YYYY-MM-DD'
                        );
                    }
                    for (let item of this.chatrecordlist) {
                        if (item.contentType === '3') {
                            if (
                                item.content.indexOf('.amr') !== -1 ||
                                item.content.indexOf('.AMR') !== -1
                            ) {
                                item.show = true;
                                item.loading = false;
                            } else {
                                item.show = false;
                            }
                        }
                    }
                    this.spinShow = false;
                });
            },
            changetime (time) {
                let timer = time.split(' ')[1];
                let dates = new Date();
                let date = new Date(time);
                let year = date.getFullYear();
                let years = dates.getFullYear();
                let month = date.getMonth();
                let months = dates.getMonth();
                let day = date.getDate();
                let days = dates.getDate();
                let times = '';
                if (year === years) {
                    if (month === months) {
                        if (days - day > 1) {
                            times = time;
                        } else if (days - day > 0) {
                            times = `昨天${timer}`;
                        } else {
                            times = `今天${timer}`;
                        }
                    } else {
                        times = time;
                    }
                } else {
                    times = time;
                }
                return times;
            },
            scrollTop () {
                document.querySelector('.wrapper').scrollTop = 0;
            },
            toLoading (index) {
                this.chatrecordlist[index].loading = true;
                this.chatrecordlist = JSON.parse(
                    JSON.stringify(this.chatrecordlist)
                );
                customerwechatconverfile({
                    id: this.chatrecordlist[index].id
                }).then((res) => {
                    this.chatrecordlist[index].content = res.content.replace('http://', 'https://');
                    this.chatrecordlist[index].loading = false;
                    this.chatrecordlist[index].show = false;
                    this.chatrecordlist = JSON.parse(
                        JSON.stringify(this.chatrecordlist)
                    );
                }).catch(() => {
                    this.chatrecordlist[index].loading = false;
                })
            },
            exportchat () {
                let apiBaseURL = this.$Setting.apiBaseURL
                let url = '/v1/patient/index/download-message'
                let wechat_id = `wechat_id=${this.paramsrecord.wechat_id}`
                let friend_id = `friend_id=${this.paramsrecord.friend_id}`
                let urls = `${apiBaseURL}${url}?${wechat_id}&${friend_id}`
                // window.location.href = urls
                window.open(urls);
            },
            // 查看大图
            leftimgClick (item) {
                wechatMessageInfo({id: item.id}).then(res => {
                    this.is_img = true;
                    this.content = true;
                    // 渲染数据
                    this.bigImgUrl = res.fileUrl || res.content;
                });
            },
            // 查看视频
            leftvideoClick (item) {
                wechatMessageInfo({id: item.id}).then(res => {
                    this.is_img = false;
                    this.content = true;
                    // 渲染数据
                    this.bigImgUrl = res.content;
                });
            },
            // base64解码 & 不同类型的消息解读
            decode (chat) {
                let content = chat.content;
                let jcontent = {};
                let jsonReg = /^{.*}$/;
                let thumb = '';
                let str = '';
                try {
                    switch (parseInt(chat.contentType)) {
                        // 文本 1
                        case 'Text':
                        case 1:
                            return phiz.qqFaceImgMap(content);
                        // 图片 2
                        case 'Picture':
                        case 2:
                            if (jsonReg.test(content)) {
                                jcontent = JSON.parse(content);
                                thumb = jcontent.content ? jcontent.content : '../../assets/images/imgerror.png';
                            } else {
                                thumb = content;
                            }
                            return thumb;
                        // 语音 3
                        case 'Voice':
                        case 3:
                            thumb = content.replace(/.amr/, '.mp3');
                            str = thumb.replace(/.mp3:.*/, '.mp3');

                            // str = ` <audio src="${thumb}" alt="语音" controls></audio>`
                            return str;
                        // 视频 4
                        case 'Video':
                        case 4:
                            thumb = chat.thumb ? chat.thumb : '../../assets/images/imgerror.png';
                            return thumb;
                        // 系统消息 5
                        case 'System':
                        case 5:
                            return content;
                        // 链接消息 6
                        case 'Link':
                        case 6:
                            return '<div style="color:red">有超链接消息，请在手机查看</div>';
                        // 位置信息 10
                        case 'Location':
                        case 10:
                            return '<div style="color:red">有位置消息，请在手机查看</div>';
                        // 红包 11
                        case 'LuckyMoney':
                        case 11:
                            return '<div style="color:red">有红包，请在手机查看</div>';
                        // 转账 12
                        case 'MoneyTrans':
                        case 12:
                            return '<div style="color:red">有转账，请在手机查看</div>';
                        // Emoji 14
                        case 'Emoji':
                        case 14:
                            if (chat.IsSend === 1) {
                                return `Emoji消息：${content}`;
                            } else {
                                if (jsonReg.test(content)) {
                                    jcontent = JSON.parse(content);
                                    thumb = jcontent.Thumb ? jcontent.Thumb : '../../assets/images/imgerror.png';
                                } else {
                                    thumb = content;
                                }
                                str = `<img class="chat-img" src="${thumb}" alt="图片"/>`;
                                return str;
                            }
                        default:
                            return `不支持的消息，请去手机查看`;
                    }
                } catch (error) {
                    return chat.contentType + '消息：' + content;
                }
            },
        },
    };
</script>

<style lang="less" scoped>
.wrapper {
    width: 100%;
    border-radius: 5px;
    height: 400px;
    padding: 10px;
    background: #eee;
    box-sizing: border-box;
    position: relative;
    //   background: #f3f3f3;
    overflow: auto;

    .create_time {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .wrappertitle {
        margin: 10px 0;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .right {
        // text-align: right;
        display: flex;
        flex-direction: column;
        align-items: flex-end;

        .name {
            flex-direction: row-reverse;
            .names {
                text-align: right;
            }
            img {
                margin-right: 0 !important;
            }
        }

        .content {
            .wechatchat {
                padding: 10px 15px;
                margin-bottom: 20px;
                background-color: #dae9f2;
                // text-align: center;
                border-radius: 8px;
                // box-shadow: 2px 2px 5px #000;
            }
        }
    }

    .left {
        // text-align: right;
        display: flex;
        flex-direction: column;
        align-items: flex-start;

        .content {
            .wechatchat {
                padding: 10px 15px;
                margin-bottom: 20px;
                background-color: #fff;
                // text-align: center;
                border-radius: 8px;
                // box-shadow: 2px 2px 5px #000;
            }
        }
    }
    .content {
        margin: 0 51px;
    }

    .name,
    .more {
        color: #42a2e2;
        margin-bottom: 10px;
    }

    .name {
        display: flex;
        align-items: center;
        justify-content: center;

        img {
            width: 36px;
            height: 36px;
        }
    }

    .more {
        cursor: pointer;
    }

    .content {
        .money {
            display: flex;
            align-items: center;
            width: 300px;
            height: 50px;
            padding: 10px;
            background: #fa9d3b;
            border-radius: 10px;

            .text {
                margin-left: 20px;
                color: #fff;
                font-weight: bold;
            }
        }

        .image {
            height: 100px;
        }

        .video-item {
            height: 300px;
            width: 100%;
        }

        .large-img {
            cursor: pointer;
        }
    }

    /*定义滚动条宽高及背景，宽高分别对应横竖滚动条的尺寸*/

    &::-webkit-scrollbar {
        width: 10px;
        /*对垂直流动条有效*/
        height: 10px;
        /*对水平流动条有效*/
    }

    /*定义滚动条的轨道颜色、内阴影及圆角*/
    &::-webkit-scrollbar-track {
        // -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,.3);
        background-color: #fff;
        border-radius: 3px;
    }

    /*定义滑块颜色、内阴影及圆角*/
    &::-webkit-scrollbar-thumb {
        border-radius: 7px;
        -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
        // background-color: #ccc;
        background-color: #eee;
    }

    // /*定义两端按钮的样式*/
    // &::-webkit-scrollbar-button {
    // background-color:cyan;
    // }

    /*定义右下角汇合处的样式*/
    &::-webkit-scrollbar-corner {
        background: khaki;
    }

    .norecord {
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        margin: auto;
        display: flex;
        align-items: center;
        justify-content: center;
    }
}

.video-box {
    position: relative;
    max-height: 200px;
    overflow: hidden;
    &s {
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        margin: auto;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 28px;
    }
}
</style>